<template>
  <div class="employee-container">
    <div class="sidemenu">
      <el-menu
        default-active="2"
        class="el-menu-vertical-demo"
        @open="handleOpen"
        @close="handleClose"
      >
        <el-submenu index="1">
          <template slot="title">
            <span>国科科技</span>
          </template>
          <el-menu-item v-for="(item, index) in departData" :key="index">{{
            item.name
          }}</el-menu-item>
        </el-submenu>
      </el-menu>
    </div>
    <div class="main">
      <div class="from">
        <div class="from-input">
          <span>用户名称</span>
          <el-input placeholder="请输入用户名称" v-model="input2"> </el-input>
        </div>
        <div class="from-input">
          <span>手机号码</span>
          <el-input placeholder="请输入手机号码" v-model="input3"> </el-input>
        </div>
        <el-button type="primary" @click="inquireUser">查询</el-button>
        <el-button type="primary" @click="useradd">重置</el-button>
      </div>
      <div class="btn">
        <el-button type="primary" plain icon="el-icon-plus" @click="adduser"
          >新增</el-button
        >
        <el-button type="success" plain icon="el-icon-plus" disabled
          >修改</el-button
        >
        <el-button type="danger" plain icon="el-icon-plus" disabled
          >删除</el-button
        >
      </div>

      <el-dialog
        :title="isTrue ? '添加用户' : '修改用户'"
        :visible.sync="dialogFormVisible"
      >
        <el-form :model="form">
          <div class="add-form">
            <el-form-item label="登录名称" :label-width="formLabelWidth">
              <el-input v-model="form.loginName" autocomplete="off"></el-input>
            </el-form-item>

            <el-form-item
              class="depart-item"
              label="部门"
              :label-width="formLabelWidth"
            >
              <el-select v-model="form.deptName" placeholder="请选择">
                <el-option
                  v-for="(item, index) in depart"
                  :key="index"
                  :value="item.name"
                  :label="item.name"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="add-form">
            <el-form-item label="手机号码" :label-width="formLabelWidth">
              <el-input v-model="form.phone" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" :label-width="formLabelWidth">
              <el-input v-model="form.email" autocomplete="off"></el-input>
            </el-form-item>
          </div>
          <div class="add-form">
            <el-form-item label="用户名称" :label-width="formLabelWidth">
              <el-input v-model="form.userName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="用户密码" :label-width="formLabelWidth">
              <el-input v-model="form.password" autocomplete="off"></el-input>
            </el-form-item>
          </div>
          <div class="add-form">
            <el-form-item
              class="depart-item"
              label="性别"
              :label-width="formLabelWidth"
            >
              <el-select v-model="form.gender" placeholder="请选择">
                <el-option label="男" value="1"> </el-option>
                <el-option label="女" value="0"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              class="depart-item"
              label="角色权限"
              :label-width="formLabelWidth"
            >
              <el-select v-model="form.roleName" placeholder="请选择">
                <el-option
                  v-for="(item, index) in roleList"
                  :key="index"
                  :value="item.name"
                  :label="item.name"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </div>

          <!-- 图片上传 -->
          <el-upload
            list-type="picture"
            action=""
            accept=".jpg, .png"
            :limit="1"
            :auto-upload="false"
            :file-list="fileList"
            :on-change="getFile"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleUploadRemove"
          >
            <el-button size="small" type="primary">选择图片上传</el-button>
            <!-- <div slot="tip" class="el-upload__tip">只能上传一张jpg/png文件</div> -->
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" append-to-body>
            <img width="100%" :src="dialogImageUrl" alt />
          </el-dialog>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button
            v-if="isTrue == true"
            type="primary"
            @click="dialogFormVisible = false"
            v-on:click="addlist"
            >确 定</el-button
          >

          <el-button
            v-else
            type="primary"
            @click="dialogFormVisible = false"
            v-on:click="updatelist"
            >确 定</el-button
          >
        </div>
      </el-dialog>

      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        fit
        highlight-current-row
      >
        <el-table-column label="ID" width="118.5">
          <template slot-scope="scope">
            {{ scope.row.id }}
          </template>
        </el-table-column>
        <el-table-column label="员工姓名" width="158.5">
          <template slot-scope="scope">
            {{ scope.row.userName }}
          </template>
        </el-table-column>
        <el-table-column label="部门" width="158.5">
          <template slot-scope="scope">
            {{ scope.row.deptName }}
          </template>
        </el-table-column>
        <el-table-column label="邮箱" width="158.5">
          <template slot-scope="scope">
            <span>{{ scope.row.email }}</span>
          </template>
        </el-table-column>
        <el-table-column class-name="status-col" label="手机号码" width="158.5">
          <template slot-scope="scope">
            {{ scope.row.phone }}
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="角色" width="158.5">
          <template slot-scope="scope">
            {{ scope.row.roleName }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="用户密码" width="118.5">
          <template slot-scope="scope">
            {{ scope.row.password }}
          </template>
        </el-table-column> -->
        <el-table-column label="创建时间" width="158.5">
          <template slot-scope="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="237">
          <template slot-scope="scope">
            <el-button
              class="el-icon-edit-outline"
              size="mini"
              v-on:click="updateadd(scope.row)"
              type="text"
              @click="dialogFormVisible = true"
              >修改</el-button
            >
            <el-button
              class="el-icon-lock"
              size="mini"
              type="text"
              v-on:click="reset(scope.row.id)"
              @click="dialogFormVisible1 = true"
              >重置</el-button
            >
            <el-button
              class="el-icon-delete"
              size="mini"
              type="text"
              @click="deletelist(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pagination.limit"
        :page-count="pagination.totalpage"
        @current-change="handleCurrentChange"
        :current-page="page"
      >
      </el-pagination>
    </div>

    <!-- <img :src="image" alt=""> -->
    <el-dialog title="提示" :visible.sync="dialogFormVisible1">
      <el-form>
        <div>
          <el-form-item label="新密码" :label-width="formLabelWidth">
            <el-input v-model="input8" autocomplete="off"></el-input>
          </el-form-item>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">取 消</el-button>
        <el-button
          v-if="isTrue == true"
          type="primary"
          @click="dialogFormVisible1 = false"
          v-on:click="resetPwd"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRole } from "@/api/role";
import { getDepart } from "@/api/depart";
import {
  adduser,
  getUser,
  updatesUser,
  deleteUser,
  resetPwd,
} from "@/api/user";
export default {
  data() {
    return {
      //预览图片数据
      dialogVisible: false,
      dialogImageUrl: "",


      pagination: {
        limit: 5,
        totalpage: "",
      },
      total: 0,
      page: 1,
      //上传图片数据
      fileList: [],

      image: "",

      resetuserId: "",
      dialogFormVisible1: false,
      input8: "",
      imageUrl: "",
      isTrue: true,
      radio: 1,
      dialogFormVisible: false,

      list: [],
      value1: "",
      value: "",
      formLabelWidth: "120px",
      form: {
        userName: "",
        loginName: "",
        password: "",
        deptName: "",
        roleName: "",
        remark: "",
        image: "",
        phone: "",
        email: "",
        age: "",
        gender: "",
        education: "",
      },
      listLoading: false,
      input2: "",
      input3: "",
      filterText: "",
      departData: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      depart: [],
      roleList: [],
    };
  },
  created() {
    this.getUser();
    this.getDepart();
    this.getRole();
    this.getpage();
    
  },
  methods: {
    //分页监听器
    async handleCurrentChange(value) {
      this.page = value;

      this.getUser();
    },
    //算页数
    getpage() {
      this.pagination.totalpage = Math.ceil(this.total / this.pagination.limit);
      console.log(this.pagination.totalpage);
    },
    fetchData() {},

    handleOpen(key, keyPath) {
      console.log(key, keyPath);
    },
    handleClose(key, keyPath) {
      console.log(key, keyPath);
    },
    //新增用户
    async addlist() {
      let arr = {
        userName: this.form.userName,
        loginName: this.form.loginName,
        password: this.form.password,
        deptName: this.form.deptName,
        roleName: this.form.roleName,
        remark: this.form.remark,
        image: JSON.parse(localStorage.getItem("images")),
        phone: this.form.phone,
        email: this.form.email,
        age: this.form.age,
        gender: this.form.gender,
        education: this.form.education,
      };
      console.log(arr);
      await adduser(arr);
      await this.getUser();

      this.$message({
        message: "添加成功",
        type: "success",
      });
      this.form = {
        userName: "",
        loginName: "",
        password: "",
        deptName: "",
        roleName: "",
        remark: "",
        image: "",
        phone: "",
        email: "",
        age: "",
        gender: "",
        education: "",
      };
      this.dialogImageUrl = "";
    },
    updateadd(value) {
      this.isTrue = false;
      this.form = value;
      console.log(this.form);
    },
    adduser() {
      this.dialogFormVisible = true;
      this.isTrue = true;
    },
    //修改用户
    async updatelist() {
      let arr = {
        id: this.form.id,
        userName: this.form.userName,
        loginName: this.form.loginName,
        deptName: this.form.deptName,
        roleName: this.form.roleName,
        phone: this.form.phone,
        email: this.form.email,
        gender: this.form.gender,
      };
      console.log(arr);
      await updatesUser(arr);
      await this.getUser();
      this.$message({
        message: "修改成功",
        type: "success",
      });
    },
    //删除用户
    async deletelist(id) {
      console.log(id);
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let obj = {
            userId: id,
          };
          deleteUser(obj).then((res) => {
            this.getUser();
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //重置input
    useradd() {
      (this.input2 = ""), (this.input3 = ""), this.getUser();
    },
    //查询用户
    inquireUser() {
      
      let obj = {
        userName: this.input2,
        phone: this.input3,
        limit: this.pagination.limit,
        page: this.page,
      };
      getUser(obj).then((res) => {
        this.list = res.data;
        this.total = res.count;
        console.log(this.total);
      });
      this.page = 1;
    },

    //获取列表
    getUser() {
      let obj = {
        userName: this.input2,
        phone: this.input3,
        limit: this.pagination.limit,
        page: this.page,
      };

      getUser(obj).then((res) => {
        this.list = res.data;
        this.total = res.count;
        console.log(this.list,"31231")
        
      });

      // console.log(this.list)
    },
    //  获取部门类表
     getDepart() {
      let obj = {
        limit: this.pagination.limit,
        page: this.page,
      };
       getDepart(obj).then(res=>{
        this.depart = res.data.records;
      this.departData = this.depart;

      })
      
    },
    // 获取角色
     getRole() {
      let obj = {
        limit: this.pagination.limit,
        page: this.page,
      };
       getRole(obj).then(res=>{
           this.roleList = res.data;


      })
     
    },
    //修改密码
    resetPwd() {
      let obj = {
        userId: this.resetuserId,
        password: this.input8,
      };
      console.log(obj);
      resetPwd(obj).then((res) => {
        this.$message({
          type: "success",
          message: "修改密码成功!",
        });
      });
    },
    reset(id) {
      this.resetuserId = id;
    },
    //获取文件
    getFile(file, fileList) {
      this.getBase64(file.raw).then((res) => {
        const params = res.split(",");
        console.log(params, "params");
        if (params.length > 0) {
          this.proofImage = params[1];
        }
      });
    },
    //图片转化成base64
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        const reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(imgResult);
          this.image = imgResult;
          console.log(this.image);
          localStorage.setItem("images", JSON.stringify(this.image));
        };
      });
    },

    handleUploadRemove(file, fileList) {
      this.proofImage = "";
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    // handleAvatarSuccess(res, file) {
    //   this.imageUrl = URL.createObjectURL(file.raw);
    // },
    // beforeAvatarUpload(file) {
    //   const isJPG = file.type === "image/jpeg";
    //   const isLt2M = file.size / 1024 / 1024 < 2;

    //   if (!isJPG) {
    //     this.$message.error("上传头像图片只能是 JPG 格式!");
    //   }
    //   if (!isLt2M) {
    //     this.$message.error("上传头像图片大小不能超过 2MB!");
    //   }
    //   return isJPG && isLt2M;
    // },
  },
};
</script>
<style scoped>
.app-container {
  display: flex;
}
.employee-header {
  display: flex;
  padding: 0;
}
.sidemenu .el-input {
  width: 100%;
  height: 40px;
}
.employee-header .el-button {
  height: 40px;
  margin-left: 10px;
}
.main .el-input {
  width: 200px;
  height: 40px;
}
.add-form {
  display: flex;
}
.sidemenu {
  padding: 0 20px;
  width: 200px;
  font-size: 14px;
}
.sidemenu .el-menu {
  border: none;
}
.sidemenu .el-input {
  margin-bottom: 20px;
}
.from-input .el-input {
  margin: 0 10px;
}
.from {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20px;
}
.main {
  width: calc(100%-200px);
  margin-top: 8px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.imgUp {
  margin-left: 54px;
  font-weight: bold;
}

</style>
<style lang="scss">
.employee-container {
  display: flex;
  .el-table th > .cell {
    text-align: center !important;
  }
  .cell {
    padding-left: 0 !important;
  }
  .el-range-editor.el-input__inner {
    margin: 0 10px;
  }

  .el-table td {
    text-align: center !important;
  }
  .el-table__body,
  .el-table__footer,
  .el-table__header {
    width: 100%;
  }
  .btn {
    margin-bottom: 10px;
  }
  .el-upload {
    margin-left: 42px;
    margin-top:6px;

  }
}
</style>
